<template>
  <PageWrapper>
    <BasicTable
      @register="registerTable"
      :rowSelection="
        checkboxShow
          ? {
              type: 'checkbox',
              columnWidth: 44,
              selectedRowKeys: checkedDelKeys,
              onChange: onSelectChange,
              getCheckboxProps: onGetCheckboxProps
            }
          : null
      "
    >
      <template #form-channelCode="{ model, field }">
        <a-tree-select
          v-model:value="model[field]"
          :tree-data="channelTreeData"
          @change="treeSelectChange(model[field])"
          multiple
          allowClear
          :field-names="{
            label: 'channelName',
            value: 'channelCode',
            children: 'children'
          }"
          treeNodeFilterProp="channelName"
          placeholder="请选择渠道名称"
          :maxTagCount="1"
          showCheckedStrategy="SHOW_ALL"
        ></a-tree-select>
      </template>
      <template #tableTitle>
        <a-space :size="12">
          <a-button type="primary" v-auth="permissionCodeMap.userAdd" @click="operateUser(operateActionTypeMap.ADD)"
            >新增用户</a-button
          >
          <a-button :disabled="!checkedDelKeys.length" danger v-auth="permissionCodeMap.userDel" @click="batchDel"
            >删除用户</a-button
          >
        </a-space>
      </template>

      <template #bodyCell="{ column, record, text }">
        <template v-if="column.dataIndex === 'rolePermit'">
          <span v-for="item in text" :key="item.roleId" style="margin: 0 5px">
            {{ item.roleName }}
          </span>
        </template>
        <template v-else-if="column.dataIndex === 'channelHead'">
          {{ record.channelHead || '--' }}
        </template>
        <template v-else-if="column.dataIndex === 'userStatus'">
          <span class="global-active-status" v-if="record.userStatus == 0"> 启用 </span>
          <span class="global-stop-status" v-else-if="record.userStatus == 1"> 停用 </span>
        </template>
        <template v-else-if="column.dataIndex === 'operate'">
          <a-button
            type="link"
            class="g-operate-btn"
            v-if="record.userId !== currentUserId"
            v-auth="permissionCodeMap.userEdit"
            @click="operateStatus(record)"
          >
            {{ record.userStatus == 0 ? '停用' : '启用' }}
          </a-button>
          <a-button
            type="link"
            v-auth="permissionCodeMap.userView"
            class="g-operate-btn"
            @click="operateUser(operateActionTypeMap.VIEW, record)"
            >查看</a-button
          >
          <a-button
            type="link"
            v-if="record.userId !== currentUserId"
            class="g-operate-btn"
            v-auth="permissionCodeMap.userEdit"
            @click="operateUser(operateActionTypeMap.EDIT, record)"
            >编辑</a-button
          >
        </template>
      </template>
    </BasicTable>
    <UserAdd @register="userAddRegister" @operateSuccess="operateSuccess" @resetPwd="userDel" />
    <UserDel @register="userDelRegister" @operateSuccess="operateSuccess" />
  </PageWrapper>
</template>

<script lang="ts" setup>
import { reactive, ref, computed, unref, watch, onMounted, createVNode } from 'vue'
import PageWrapper from '@/components/PageWrapper/index.vue'
import { BasicTable, useTable } from '@/components/Table'
import { getUserBasicColumns, getSearchFormConfig } from './dataSource'
import { useDrawer } from '@/components/Drawer'
import { useModal } from '@/components/Modal'
import UserAdd from './components/UserAdd.vue'
import UserDel from './components/UserDel.vue'
import { userStore } from '@/store/modules/user'
import { permissionCodeMap } from '@/utils/permissionCodeMap'
import { createChannelTree, transformToTree } from '@/utils'
import { operateActionType, operateTxtType, constantMap } from '@/types/enum'
import { UserRecord } from '@/types/system'
import { message, Modal } from 'ant-design-vue'
import { ExclamationCircleFilled } from '@ant-design/icons-vue'
import api from '@/api'
const { userList, queryChannelList, switchPlatformUser } = api

const userModule = userStore()

const operateActionTypeMap = operateActionType
const currentUserId = computed(() => userModule.userInfo?.userId)
const checkboxShow = computed(() => userModule.permissionActionList.includes(permissionCodeMap.userDel))
const resetPwdShow = computed(() => userModule.permissionActionList.includes(permissionCodeMap.userResetPwd))

const [registerTable, { reload, setPagination, getForm }] = useTable({
  api: userList,
  columns: getUserBasicColumns(),
  useSearchForm: true,
  beforeFetch: beforeParamsFetch,
  formConfig: getSearchFormConfig(),
  showIndexColumn: true,
  rowKey: 'userId',
  scroll: { y: constantMap.tableYHeight, x: constantMap.tableXWidth }
})

const [userAddRegister, { openDrawer: UserAddOpenDrawer, setDrawerProps }] = useDrawer()
const [userDelRegister, { openModal: userDelOpenModal }] = useModal()

const checkedDelKeys = ref<Array<string | number>>([])
const checkedDelList = ref<Array<UserRecord>>([])
const channelTreeData = ref<any>([])
const seclectedChannel = ref<any>([])

onMounted(async () => {
  const res = await queryChannelList({ channelRange: '3' })
  channelTreeData.value = transformToTree(res.result)
})

const treeSelectChange = (data: any) => {
  seclectedChannel.value = data
}
function beforeParamsFetch(params: any) {
  const { channelCode, ...rest } = params
  const { getFieldsValue } = getForm()
  const formData = getFieldsValue()
  const formChannel = formData.channelCode
  let channelCodeSet
  if (seclectedChannel.value.length > 0 && formChannel) {
    channelCodeSet = seclectedChannel.value
  }
  let paramsData = {
    ...rest,
    channelCodeSet
  }
  return paramsData
}

const onSelectChange = (selectedRowKeys: (string | number)[], selectedRow: UserRecord[]) => {
  checkedDelKeys.value = selectedRowKeys
  checkedDelList.value = selectedRow
}
// 禁止删除当前登录用户
const onGetCheckboxProps = (record: UserRecord) => {
  return {
    disabled: record.userId === currentUserId.value
  }
}
const operateUser = (type: OperateType, record?: UserRecord) => {
  setDrawerProps({
    title: operateTxtType[type],
    okText: type === operateActionTypeMap.VIEW ? '重置密码' : '确认',
    showOkBtn: type !== operateActionTypeMap.VIEW || unref(resetPwdShow),
    cancelText: type === operateActionTypeMap.VIEW ? '关闭' : '取消'
  })
  UserAddOpenDrawer(true, {
    type,
    record
  })
}

const userDel = (record: UserRecord, type?: string) => {
  userDelOpenModal(true, {
    type,
    record
  })
}
const operateStatus = (record: any) => {
  let contentInfo = record.userStatus == 1 ? '启用' : '停用'
  Modal.confirm({
    title: '提示',
    centered: true,
    icon: createVNode(ExclamationCircleFilled),
    content: `是否确认${contentInfo} ${record.userName} 的账户使用权限`,
    autoFocusButton: null,
    class: 'modal-confirm-box',
    async onOk() {
      await switchPlatformUser({
        userId: record.userId,
        userStatus: record.userStatus === 1 ? 0 : 1
      })
      message.success(`${contentInfo}账户成功`)
      reload()
    },
    onCancel() {}
  })
}
const batchDel = () => {
  userDelOpenModal(true, {
    type: 'batchDel',
    checkedDelKeys: checkedDelKeys.value,
    checkedDelList: checkedDelList.value
  })
}
const operateSuccess = () => {
  setPagination({
    current: 1
  })
  reload()
}
</script>

<style lang="less" scoped></style>
